import bpy
from bpy.types import Operator
import os
import geopandas as gpd
from pymap3d import ecef
import math

def drawPipe(name,path_points,radius,segments):

    # 创建贝塞尔曲线并设置路径点
    bpy.ops.curve.primitive_bezier_curve_add()
    curve = bpy.context.object
    curve.name = "PipePath"

    # 获取曲线的Bezier点
    bezier_points = curve.data.splines[0].bezier_points
    # 确保点的数量与path_points相同
    curve.data.splines[0].bezier_points.add(len(path_points) - len(bezier_points))
    for i, point in enumerate(path_points):
        bezier_points[i].co = point
        bezier_points[i].handle_left_type = 'VECTOR'
        bezier_points[i].handle_right_type = 'VECTOR'

    # 创建管道
    # bpy.ops.object.select_all(action='DESELECT')
    # curve.select_set(True)
    # bpy.context.view_layer.objects.active = curve

    # 设置曲线的分辨率
    # curve.data.resolution_u = 200

    # 可选：移除曲线的可见性
    curve.data.bevel_depth = radius
    curve.data.bevel_resolution = segments
    # curve.data.use_fill_caps = True

    # 转换曲线为网格
    bpy.ops.object.convert(target='MESH')
    obj = bpy.context.object
    obj.name = name

    new_mat = bpy.data.materials.new(name=name)
    new_mat.use_nodes = True
    new_mat.node_tree.nodes["Principled BSDF"].inputs[0].default_value = (0.0, 1.0, 0.0, 1)
    obj.data.materials.append(new_mat)

    # 更新场景xaxax
    bpy.context.view_layer.update()





class Auto_Draw_Pipe(Operator):
    bl_idname = "object.auto_draw_pipe"
    bl_label = "自动画管线"
    bl_description = "使用geojson自动化管线"

    # @classmethod
    # def poll(cls,context):
    #     pipe_path = context.scene.pipe_path

    #     if os.path.exists(pipe_path) and os.path.splitext(pipe_path)[-1].lower()=='.geojson':
    #         return True

    #     return False

    def execute(self,context):
        pipe_data = gpd.read_file(r"C:\Users\小米PC\Desktop\zx3d.geojson")

        # 计算中心点
        centroid = pipe_data['geometry'].unary_union.centroid
        print(centroid)

        # 计算所有坐标点
        lines = {}
        for i in range(len(pipe_data)):
            coords = []
            diameter = int(pipe_data.loc[i,'管径'])/1000
            for coord in pipe_data.loc[i,'geometry'].coords:
                ecef_x,ecef_y,ecef_z = ecef.geodetic2ecef(coord[1], coord[0], coord[2])
                enu_e,enu_n,enu_u = ecef.ecef2enu(ecef_x,ecef_y,ecef_z,centroid.y,centroid.x,0)
                coords.append((float(enu_e),float(enu_n),float(enu_u)))
            lines[i] = (coords,diameter)

            # 画管线
            drawPipe('pipe'+str(i),coords,diameter,8)


        return {'FINISHED'}

    
